package com.qianfeng.smartdevice.event.listeners;

import com.qianfeng.smartdevice.enums.LoginResultEnum;
import com.qianfeng.smartdevice.event.MyloginEvent;
import com.qianfeng.smartdevice.mapper.SysLogininforMapper;
import com.qianfeng.smartdevice.mapper.SysUserOnlineMapper;
import com.qianfeng.smartdevice.pojo.SysLogininfor;
import com.qianfeng.smartdevice.pojo.SysUserOnline;
import com.qianfeng.smartdevice.utils.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * Created by wenka on 2022/3/20 17:02
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Component
public class LoginEventListener {
    private SysLogininforMapper sysLogininforMapper;
    Logger logger = LoggerFactory.getLogger(LoginEventListener.class);

    @Autowired
    public void setSysLogininforMapper(SysLogininforMapper sysLogininforMapper) {
        this.sysLogininforMapper = sysLogininforMapper;
    }

    private SysUserOnlineMapper sysUserOnlineMapper;

    @Autowired
    public void setSysUserOnlineMapper(SysUserOnlineMapper sysUserOnlineMapper) {
        this.sysUserOnlineMapper = sysUserOnlineMapper;
    }

    @EventListener
    public void onEvent(MyloginEvent event) {
        logger.error("接收到登录事件了");
        //获取request
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        CompletableFuture.runAsync(() -> {
            HttpServletRequest request = requestAttributes.getRequest();
            //获取sessionId
            String sessionId = request.getSession().getId();
            //获取ip
            String ip = RequestUtil.getRemoteHost(request);
            //获取操作系统和浏览器的信息
            Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);
            //获取到ip对应的地区
            String locationByIp = RequestUtil.getLocationByIp(ip);
//保存数据到对象中
            SysLogininfor sysLogininfor = new SysLogininfor();
            sysLogininfor.setIpaddr(ip);
            sysLogininfor.setLoginLocation(locationByIp);
            sysLogininfor.setLoginName(event.getUsername());
            sysLogininfor.setLoginTime(new Date());
            sysLogininfor.setBrowser(osAndBrowserInfo.get("browser"));
            sysLogininfor.setOs(osAndBrowserInfo.get("os"));
            switch (event.getLoginResultEnum()) {
                case SUCCESS:
                    sysLogininfor.setMsg("登陆成功");
                    sysLogininfor.setStatus("1");
                    break;
                case FAIL:
                    sysLogininfor.setMsg("登录失败");
                    sysLogininfor.setStatus("0");
                    break;
            }
            System.err.println(sysLogininfor);
            sysLogininforMapper.addLoginLog(sysLogininfor);
            if (event.getLoginResultEnum() == LoginResultEnum.SUCCESS) {
                //在登录成功之后还需要更新下在线用户
                //在线用户的数据中我们只有一个数据不知道，sessionId，我们已经拿到request了，只需要通过他拿到sessionId
                SysUserOnline sysUserOnline = new SysUserOnline();
                BeanUtils.copyProperties(sysLogininfor, sysUserOnline);
                sysUserOnline.setSessionId(sessionId);
                sysUserOnline.setExpireTime(30L);
                sysUserOnline.setStartTimestamp(new Date());
                logger.error("在线用户的信息" + sysUserOnline);
                //保存到数据库
                int count = sysUserOnlineMapper.findByUserName(sysUserOnline.getLoginName());
                if (count == 1) {
                    //如果有数据就更新
                    sysUserOnlineMapper.updateSysUserOnline(sysUserOnline);
                } else {
                    //如果没有就添加
                    sysUserOnlineMapper.addSysUserOnline(sysUserOnline);
                }
            }
        });


    }
}
